package com.yjq.programmer.service.impl;

import com.alibaba.fastjson.JSON;
import com.yjq.programmer.bean.CodeMsg;
import com.yjq.programmer.dao.UserMapper;
import com.yjq.programmer.domain.User;
import com.yjq.programmer.domain.UserExample;
import com.yjq.programmer.dto.LoginDTO;
import com.yjq.programmer.dto.ResponseDTO;
import com.yjq.programmer.dto.UserDTO;
import com.yjq.programmer.enums.RoleEnum;
import com.yjq.programmer.service.IUserService;
import com.yjq.programmer.utils.CommonUtil;
import com.yjq.programmer.utils.CopyUtil;
import com.yjq.programmer.utils.EmojiConverterUtil;
import com.yjq.programmer.utils.UuidUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 杨杨吖
 * @QQ 823208782
 * @WX yjqi12345678
 * @create 2023-09-25 17:08
 */
@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 填写上你的AppID，如何获取AppID自行百度，这步骤很简单
    private final static String APP_ID = "wxc41c88e07f3f1bd7";
    // 填写上你的AppSecret，如何获取AppSecret自行百度，这步骤很简单
    private final static String APP_SECRET = "99a06dc0d1e21d797a9915baca08c872";
    // 微信小程序登录校验请求地址
    private final static String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 小程序授权登录验证
     * @param userDTO
     * @return
     */
    @Override
    public ResponseDTO<UserDTO> appWxLogin(UserDTO userDTO) {
        String url = LOGIN_URL + "?appid=" + APP_ID + "&secret="+ APP_SECRET + "&grant_type=authorization_code&js_code=" + userDTO.getCode();
        HttpClient client = HttpClients.createDefault(); // 创建默认http连接
        HttpGet getRequest = new HttpGet(url);// 创建一个post请求
        LoginDTO loginDTO = new LoginDTO();
        try {
            // 用http连接去执行get请求并且获得http响应
            HttpResponse response = client.execute(getRequest);
            // 从response中取到响实体
            HttpEntity entity = response.getEntity();
            // 把响应实体转成文本
            String html = EntityUtils.toString(entity);
            loginDTO = JSON.parseObject(html, LoginDTO.class);
            if(null == loginDTO.getErrcode()) {
                userDTO.setWxId(loginDTO.getOpenid());
            } else {
                return ResponseDTO.errorByMsg(CodeMsg.USER_WX_LOGIN_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.errorByMsg(CodeMsg.USER_WX_LOGIN_ERROR);
        }
        // 使用微信openId查询是否有此用户
        UserExample userExample = new UserExample();
        userExample.createCriteria().andWxIdEqualTo(userDTO.getWxId());
        List<User> userList = userMapper.selectByExample(userExample);
        if(null != userList && userList.size() > 0) {
            // 已经存在用户信息，读取数据库中用户信息
            User user = userList.get(0);
            userDTO = CopyUtil.copy(user, UserDTO.class);
        } else {
            // 数据库中不存在，注册用户信息
            User user = CopyUtil.copy(userDTO, User.class);
            user.setId(UuidUtil.getShortUuid());
            user.setUsername(EmojiConverterUtil.emojiConvert(user.getWxUsername()));
            user.setWxUsername(EmojiConverterUtil.emojiConvert(user.getWxUsername()));
            user.setHeadPic(user.getWxHeadPic());
            user.setRoleId(RoleEnum.USER.getCode());
            if(userMapper.insertSelective(user) == 0) {
                return ResponseDTO.errorByMsg(CodeMsg.USER_REGISTER_ERROR);
            }
            userDTO = CopyUtil.copy(user, UserDTO.class);
        }
        userDTO.setToken(UuidUtil.getShortUuid());
        stringRedisTemplate.opsForValue().set("USER_" + userDTO.getToken(), JSON.toJSONString(userMapper.selectByPrimaryKey(userDTO.getId())), 3600, TimeUnit.SECONDS);
        return ResponseDTO.successByMsg(userDTO, "登录成功！");
    }


    /**
     * 退出登录操作
     * @param userDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> logout(UserDTO userDTO) {
        if(!CommonUtil.isEmpty(userDTO.getToken())){
            // token不为空  清除redis中数据
            stringRedisTemplate.delete("USER_" + userDTO.getToken());
        }
        return ResponseDTO.successByMsg(true, "退出登录成功！");
    }

}
